package com.feihong.yw189.bluetooth.utils.djlm;

import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.feihong.yw189.app.App;
import com.feihong.yw189.bluetooth.server.BLEService;
import com.feihong.yw189.bluetooth.utils.util.SIMCard;
import com.inuker.bluetooth.library.Constants;
import com.inuker.bluetooth.library.connect.options.BleConnectOptions;
import com.inuker.bluetooth.library.connect.response.BleConnectResponse;
import com.inuker.bluetooth.library.model.BleGattProfile;
import com.inuker.bluetooth.library.utils.BluetoothUtils;

import java.io.IOException;

/**
 * Created by Admin on 2017/6/5.
 */

public class DJLM_ReadICCIDAndSIM {

    private String str_imsi = "";//序列号
    private String str_serialnumber = "";//手机号
    private String OrderNum = "201703225353100909";//手机号
    private String iccid = "";
    private Context mContext;
    private String macAddress;
    private BluetoothDevice mBluetoothDevice;
    private static final String TAG = "蓝牙";
    private StringBuffer buffer = new StringBuffer();
    private int BytesHaveBeenSentCount = 0;
    private boolean isDon = false;
    private BLEService mService;
    private DJLMCallBack mCallBack;
    Message message = new Message();
    int connectRetCount = 0;

    public DJLM_ReadICCIDAndSIM(Context context, String macAdd, DJLMCallBack callBack) {
        connectRetCount = 0;

        buffer = new StringBuffer();
        this.mContext = context;
        this.mBluetoothDevice = BluetoothUtils.getRemoteDevice(macAdd);
        this.macAddress = mBluetoothDevice.getAddress();
        this.mCallBack = callBack;
        startConnect();

    }

    private void startConnect() {


        Log.i(TAG, "startConnect: 第" + connectRetCount + " 测试阅读....");
        disconnect();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        message = new Message();
        connectRetCount++;
        BLEService.g_BLEService = null;
        App.getApp().getmClinet().disconnect(macAddress);
        mService = BLEService.GetBLEService(mContext);
        mService.SetSilence(true);//取消通知
        if (!mService.initialize()) {
            Log.i(TAG, "DJLM_ReadICCID: 无法初始化蓝牙服务！");
            if (connectRetCount > 3) {
                message.what = -1;
                message.obj = "无法初始化蓝牙服务！";
                mHandler.handleMessage(message);
                return;
            }
            startConnect();//重新来一次....
            return;
        }
        //mService.connect(macAddress);


        BleConnectOptions options = new BleConnectOptions.Builder()
                .setConnectRetry(3)   // 连接如果失败重试3次
                .setConnectTimeout(10000)   // 连接超时30s
                .setServiceDiscoverRetry(3)  // 发现服务如果失败重试3次
                .setServiceDiscoverTimeout(10000)  // 发现服务超时20s
                .build();
        App.getApp().getmClinet().connect(macAddress, options, new BleConnectResponse() {
            @Override
            public void onResponse(int code, BleGattProfile data) {
                if (code == Constants.REQUEST_SUCCESS) {
                    Log.i(TAG, "DJLM_ReadICCID: REQUEST_SUCCESS！");
                    if (mService.connect(macAddress, DJLM_ReadICCIDAndSIM.this.mBluetoothDevice)) {
                        mService.WaiteBLEConnnect(3000, 500, connectHandler);
                    } else {
                        if (connectRetCount > 3) {
                            message.what = -1;
                            message.obj = "无法初始化蓝牙服务！";
                            mHandler.handleMessage(message);
                            return;
                        }
                        startConnect();//重新来一次....
                        return;
                    }
                } else {
                    Log.i(TAG, "DJLM_ReadICCID: 无法连接蓝牙设备");
                    if (connectRetCount > 3) {
                        message.what = -1;
                        message.obj = "无法连接蓝牙设备！";
                        mHandler.handleMessage(message);
                        return;
                    }
                    startConnect();//重新来一次....
                    return;
                }
            }
        });
    }

    private Handler connectHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0: {
                    Log.i(TAG, "蓝牙连接失败!");
                    if (connectRetCount > 3) {
                        message.what = -1;
                        message.obj = "蓝牙连接失败!";
                        mHandler.handleMessage(message);
                        return;
                    }
                    startConnect();//重新来一次....
                }
                break;
                case 1: {
                    Log.i(TAG, "handleMessage: 开始读卡.....");
                    xieKa();
                }
                break;
            }
        }
    };

    private void xieKa() {
        new Thread(new Runnable() {
            private boolean qiehuanmoshi() {
                try {
                    //新版设备不需要切换模式
                    if (!mBluetoothDevice.getName().startsWith("DJLM1")) {
                        return true;
                    }
                    float ver = SIMCard.GetVerFloat(mService);
                    Log.i(TAG, "run: 设备版本:" + ver);
                    if (ver >= 1.028) {//大于1.028版本的板子才能获取高低速状态
                        int ret = 5;
                        boolean isSuccess = false;
                        while (ret > 0) {
                            int nRetInterval = SIMCard.GetInterval(mService);
                            if (nRetInterval > 20) { //大于20表示低速 ，小于20表示高速
                                isSuccess = true;
                                break;
                            }
                            SIMCard.BLEFast(mService, false);
                            SIMCard.BLEFast(mService, false);
                            ret--;
                        }
                        if (!isSuccess) {
                            message.what = -1;
                            message.obj = "无法切换低速模式，请关闭设备，重试一下！";
                            mHandler.handleMessage(message);
                            SIMCard.PowerOff(mService);//关机设备
                            disconnect();
                            return isSuccess;
                        }
                        Log.i(TAG, "run: 切换状态:" + isSuccess);
                        return isSuccess;

                    } else {//否则多次调用切换低速模式
                        try {
                            SIMCard.BLEFast(mService, false);
                            SIMCard.BLEFast(mService, false);
                            SIMCard.BLEFast(mService, false);
                            SIMCard.BLEFast(mService, false);
                            if (App.getApp().getmClinet().getConnectStatus(macAddress) != 2) {
                                return false;
                            }
                            return true;
                        } catch (Exception ex) {
                            return false;
                        }
                    }

                } catch (Exception ex) {

                    Log.i(TAG, "run: 切换高速低俗 出现错误：" + ex.getMessage());
                    return false;
                }
            }

            @Override
            public void run() {

                boolean qiehuanzhuangtai = qiehuanmoshi();
                if (!qiehuanzhuangtai) {
                    startConnect();
                    return;
                }
                connectRetCount = 100;
                //第一步连接设备
                String ICCID = "";
                String IMSI = "";
                try {
                    ICCID = SIMCard.ReadICCID(mService);
                    Log.i(TAG, "run: 第1步获取ICCID:" + ICCID);
                    IMSI = SIMCard.ReadIMSI(mService);
                    Log.i(TAG, "run: 第2步获取IMSI:" + IMSI);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (ICCID == null || ICCID.trim().length() == 0 || IMSI == null || IMSI.trim().length() == 0) {
                    Log.i(TAG, "run: 无法获取卡号，请正确插入卡片！");
                    message.what = -1;
                    message.obj = "无法获取卡号，请正确插入卡片！";
                    mHandler.handleMessage(message);
                    try {
                        SIMCard.Beep(mService);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    disconnect();
                    return;
                } else {
                    Log.i(TAG, "run: ICCID+\"|\"+IMSI=" + ICCID + "|" + IMSI);
                    try {
                        SIMCard.Beep(mService);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    message.what = 1;
                    message.obj = ICCID + "|" + IMSI;
                    mHandler.handleMessage(message);
                    disconnect();
                }

            }
        }) {
        }.start();
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (mCallBack != null) {
                if (msg.what == -1) {
                    mCallBack.error(msg.obj.toString());
                } else {
                    mCallBack.success(msg.obj.toString());
                }
            }
        }
    };

    public void disconnect() {
        try {
            if (mService != null) {
                mService.disconnect();
            }
            App.getApp().getmClinet().disconnect(macAddress);
            App.getApp().getmClinet().disconnect(macAddress);
            App.getApp().getmClinet().disconnect(macAddress);
            BLEService.g_BLEService = null;
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }


}
